import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import 'models/article.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ArticlesPage(),
    );
  }
}

class ArticlesPage extends StatefulWidget {
  const ArticlesPage({Key? key}) : super(key: key);

  @override
  _ArticlesPageState createState() => _ArticlesPageState();
}

class _ArticlesPageState extends State<ArticlesPage> {
  final Dio _dio = Dio();

  final int pageSize = 15;

  int current = 1;

  int total = 0;

  bool dataLoading = false;

  var dataList = <Article>[];

  @override
  void initState() {
    _getDataList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("billboard"),
      ),
      body: Builder(
        builder: (context) {
          if (dataLoading) {
            return Padding(
              padding: EdgeInsets.only(top: 20),
              child: Align(
                alignment: Alignment.topCenter,
                child: CircularProgressIndicator(),
              ),
            );
          } else {
            if (dataList.isEmpty) {
              return SizedBox();
            } else {
              return Column(children: [
                ListTile(title: Text("新闻列表")),
                Expanded(
                  child: ListView.builder(
                      itemCount: dataList.length + 1,
                      physics: const BouncingScrollPhysics(),
                      prototypeItem: ListTile(title: Text("1")),
                      itemBuilder: (BuildContext context, int index) {
                        print("$index");
                        // 继续获取数据
                        if (index == dataList.length) {
                          if (dataList.length == total) {
                            return Center(
                              child: ListTile(title: Text('没有更多了', textAlign: TextAlign.center, style: TextStyle(color: Colors.grey))),
                            );
                          } else {
                            current += 1;
                            Future.delayed(const Duration(seconds: 1)).then((value) => _getDataList());
                            return Center(
                              child: SizedBox.square(
                                  dimension: 20,
                                  child: CircularProgressIndicator(
                                    color: Colors.grey,
                                    strokeWidth: 2,
                                  )),
                            );
                          }
                        }
                        return ListTile(
                          title: Text(dataList[index].title!),
                        );
                      }),
                ),
              ]);
            }
          }
        },
      ),
    );
  }

  void _getDataList() async {
    dataLoading = true;
    var response = await _dio.get("https://api.jingdiansxj.cn/api/news/page?current=$current&size=$pageSize");
    setState(() {
      var res = response.data;
      var dList = (res["data"]["records"] as List).map((e) => Article.fromJson(e)).toList();
      dataList.insertAll(dataList.length, dList);
      total = res["data"]["total"];
      dataLoading = false;
    });
  }
}
